package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.ByteUtil;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.model.UltrasonicDevice;
import com.firefightingiot.firefightingiot.model.UltrasonicDeviceNormalLog;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.DayUtil;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import com.firefightingiot.firefightingiot.web.mapper.UltrasonicDeviceMapper;
import com.firefightingiot.firefightingiot.web.mapper.UltrasonicDeviceNormalLogMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: YangYu
 * @ClassName: UltrasonicDeviceNormalLog
 * @Date: Created in 10:05 2022/10/9
 * @Description:
 */
@Service
public class UltrasonicDeviceNormalLogService extends BaseService {

    @Resource
    private UltrasonicDeviceMapper ultrasonicDeviceMapper;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private UltrasonicDeviceNormalLogMapper ultrasonicDeviceNormalLogMapper;

    /**
     * @Author YangYu
     * @Description 定时用命令获取今日累计流量(每天23点30分执行)
     * @Date Created in 10:46 2022/10/9
     */
    //@Scheduled(cron="0 30 23 * * ?")
    public void getTodayValue() {
        //总水表
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("device_classify", "18").eq("product_id", "9001"));
        //分水表
        List<UltrasonicDevice> ultrasonicDeviceList = ultrasonicDeviceMapper.selectList(new QueryWrapper<UltrasonicDevice>().eq("device_classify", "18").eq("product_id", "9001"));

        for (DeviceBusiness deviceBusiness : deviceBusinessList) {
            JSONObject data = new JSONObject();
            data.put("number", deviceBusiness.getTransDeviceCode());
            String returnCode = hex10To16s(Integer.parseInt(deviceBusiness.getNumber().replace("4A5A", ""))) + "0300880002";
            String crc = ByteUtil.getCRC(ByteUtil.hex2byte(returnCode));
            //组装下发指令
            data.put("code", returnCode + crc.substring(2, 4) + crc.substring(0, 2));
            //下发指令
            rest(data, "ultrasonicClient", "ultrasonicClient", "tcp", "POST");
        }
        for (UltrasonicDevice ultrasonicDevice : ultrasonicDeviceList) {
            JSONObject data = new JSONObject();
            data.put("number", ultrasonicDevice.getTransDeviceCode());
            String returnCode = hex10To16s(Integer.parseInt(ultrasonicDevice.getNumber().replace("4A5A", ""))) + "0300880002";
            String crc = ByteUtil.getCRC(ByteUtil.hex2byte(returnCode));
            //组装下发指令
            data.put("code", returnCode + crc.substring(2, 4) + crc.substring(0, 2));
            //下发指令
            rest(data, "ultrasonicClient", "ultrasonicClient", "tcp", "POST");
        }
    }

    /**
     * @Author YangYu
     * @Description 超声波水表正常数据添加
     * @Date Created in 11:07 2022/10/9
     * @Param [jsonParam]
     */

    public RespEntity setNormalLog(JSONObject jsonParam){
        //数据
        String code = jsonParam.getStr("code");
        if (code.length() == 88){
            return RespEntity.success();
        }
        //传输装置心跳
        if (code.length() == 15){
            UltrasonicDevice ultrasonicDevice = new UltrasonicDevice();
            ultrasonicDevice.setCurrentstate("1");
            ultrasonicDevice.setNormalUpdateTime(DateUtil.now());
            ultrasonicDeviceMapper.update(ultrasonicDevice,new QueryWrapper<UltrasonicDevice>().eq("trans_device_code",code));
            DeviceBusiness deviceBusiness = new DeviceBusiness();
            deviceBusiness.setCurrentstate("1");
            deviceBusiness.setNormalUpdateTime(DateUtil.now());
            deviceBusinessMapper.update(deviceBusiness,new QueryWrapper<DeviceBusiness>().eq("trans_device_code",code));
            return RespEntity.success();
        }
        //设备详情
        UltrasonicDevice ultrasonicDevice = ultrasonicDeviceMapper.getUltrasonicDevice("4A5A"+code.substring(0,2));
        if (ultrasonicDevice == null){
            return RespEntity.fail("设备不存在");
        }
        //获取昨天的数据
        UltrasonicDeviceNormalLog deviceNormalLog = ultrasonicDeviceNormalLogMapper.selectOne(new QueryWrapper<UltrasonicDeviceNormalLog>().like("data_time",DayUtil.getYestodayForStatistics("yyyy-MM-dd")).eq("number",ultrasonicDevice.getNumber()));
        UltrasonicDeviceNormalLog ultrasonicDeviceNormalLog = new UltrasonicDeviceNormalLog();
        ultrasonicDeviceNormalLog.setId(UUID.randomUUID().toString());
        ultrasonicDeviceNormalLog.setDeviceId(ultrasonicDevice.getId());
        ultrasonicDeviceNormalLog.setNumber(ultrasonicDevice.getNumber());
        ultrasonicDeviceNormalLog.setDataTime(DateUtil.now());
        ultrasonicDeviceNormalLog.setBusinessId(ultrasonicDevice.getBusinessId());
        ultrasonicDeviceNormalLog.setBusinessName(ultrasonicDevice.getBusinessName());
        ultrasonicDeviceNormalLog.setAllId(ultrasonicDevice.getAllId());
        //计算今日累计流量
        String todayValueCode = code.substring(10,14)+code.substring(6,10);
        Integer todayValue = Integer.parseInt(todayValueCode,16);
        ultrasonicDeviceNormalLog.setTodayValue(todayValue);
        Integer cumulativeValue = 0;
        if (deviceNormalLog !=null){
            cumulativeValue = deviceNormalLog.getCumulativeValue();
        }
        ultrasonicDeviceNormalLog.setCumulativeValue(todayValue+cumulativeValue);
        ultrasonicDeviceNormalLogMapper.insert(ultrasonicDeviceNormalLog);
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 超声波水表数据分页列表
     * @Date Created in 15:49 2022/10/9
     * @Param [jsonParam]
     */

    public RespEntity ultrasonicDeviceNormalLogListPage(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if(userType.equals("1")){
            jsonParam.put("orgId",homeId);
        }else if(userType.equals("2")){
            jsonParam.put("businessId",homeId);
        }
        Page<UltrasonicDeviceNormalLog> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<UltrasonicDeviceNormalLog> pageList = ultrasonicDeviceNormalLogMapper.ultrasonicDeviceNormalLogListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 超声波总表日用水量和分表日用水量比较（分表大于总表触发用水异常、定时执行）
     * @Date Created in 9:28 2022/10/12
     */
    @Scheduled(cron="0 45 23 * * ?")
    public RespEntity compare() throws ParseException {
        //获取所有的总表
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("device_classify","18"));
        //获取所有的分水表
        List<UltrasonicDevice> ultrasonicDeviceList = ultrasonicDeviceMapper.selectList(new QueryWrapper<>());
        if (deviceBusinessList.size() <=0 || ultrasonicDeviceList.size() <=0){
            return RespEntity.fail("无比对设备");
        }
        //获取所有设备的日累计流量
        List<UltrasonicDeviceNormalLog> ultrasonicDeviceNormalLogList = ultrasonicDeviceNormalLogMapper.selectList(new QueryWrapper<UltrasonicDeviceNormalLog>().like("data_time",DayUtil.getTodayForStatistics("yyyy-MM-dd")));
        //遍历总水表
        for (DeviceBusiness deviceBusiness : deviceBusinessList){
            //总表日用流量
            int totalValue = 0;
            //分表日用流量
            int branchValue = 0;
            if (StrUtil.isNotBlank(deviceBusiness.getUltrasonicGroupId())){

                for (UltrasonicDeviceNormalLog ultrasonicDeviceNormalLog : ultrasonicDeviceNormalLogList){
                    if (deviceBusiness.getId().equals(ultrasonicDeviceNormalLog.getDeviceId())){
                        totalValue =ultrasonicDeviceNormalLog.getTodayValue();
                    }
                }
                for (UltrasonicDevice ultrasonicDevice : ultrasonicDeviceList){
                    if (deviceBusiness.getUltrasonicGroupId().equals(ultrasonicDevice.getGroupId())){
                        for (UltrasonicDeviceNormalLog ultrasonicDeviceNormalLog : ultrasonicDeviceNormalLogList){
                            if (ultrasonicDevice.getId().equals(ultrasonicDeviceNormalLog.getDeviceId())){
                                branchValue =branchValue + ultrasonicDeviceNormalLog.getTodayValue();
                            }
                        }
                    }
                }
                if (branchValue > totalValue){
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("deviceClassify","18");
                    jsonParam.put("orgIds",deviceBusiness.getAllId());
                    jsonParam.put("businessName",deviceBusiness.getBusinessName());
                    jsonParam.put("number",deviceBusiness.getNumber());
                    jsonParam.put("alarmtime",DateUtil.now());
                    jsonParam.put("position",deviceBusiness.getPosition());
                    jsonParam.put("content","分支水表日用水量大于总水表日用水量");
                    //rest请求单位详情接口，获取单位信息
                    JSONObject jsonParamN = new JSONObject();
                    jsonParamN.put("id", deviceBusiness.getBusinessId());
                    com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
                    if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
                        return RespEntity.fail(businessDetail.getString("msg"));
                    jsonParam.put("oneResponPersonName",businessDetail.getString("oneResponPersonName"));
                    jsonParam.put("oneResponPersonPhone",businessDetail.getString("oneResponPersonPhone"));
                    System.out.println(jsonParam);
                    //msgPushService.weChatMsgPush(jsonParam);
                }
            }
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 十进制转十六进制
     * @Date Created in 10:48 2021/12/15
     * @Param [value]
     */

    public static String hex10To16s(int value) {
        String hex = Integer.toHexString(value);
        if (hex.length() == 1) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static void main(String[] args) {
        String s = "864452061053748";
        System.out.println(s.length());
    }
}
